<?php

namespace app\api\logic;
use app\data\util\HttpUtil;
use think\facade\Db;

class MabangOrderLogic extends BasicLogic
{


    /**
     * @desc   获取登录接口的token
     * @author luckyXiong
     * @date   2025-05-22
     */
    public function get_authorization($params=[]){
        $content   = $params['content']??'';
        $content   = json_encode($content);
        $authorization = hash_hmac("sha256", $content, Config('Logisticskey.mabang_key.api_token'),);
        return $authorization;
    }



    /**
     * @desc   获取sku的库存信息接口
     * @author luckyXiong
     * @date   2025-05-22
     */
    public function get_sku_stock($params=[]){
        $api       = 'stock-get-stock-quantity';
        $reqParams = $params;
        $timestamp = strval(time());
        $data      =  [
            'api'       => strval($api),
            'appkey'    => Config('Logisticskey.mabang_key.api_key'),
            'data'      => $reqParams,
            'timestamp' => $timestamp,
        ];
        $url      = Config('Logisticskey.mabang_key.url');
        $token    = self::get_authorization(['content'=>$data]);
        $response = HttpUtil::postUrlMaBang($url,$data,$token);
        $info     = $response['data']['data'][0]['warehouse']??[];
        $quantity = 0;
        if($info){
            $res = end($info);
            $quantity = $res['availableStockQuantity']??'0';
        }
        return $quantity;
    }



    /**
     * @desc   获取商品行号
     * @author luckyXiong
     * @date   2025-05-22
     */
    public function get_salesRecordNumber($params=[]){
        $api       = 'order-get-order-list-new';
        $reqParams = $params;
        $timestamp = strval(time());
        $data      =  [
            'api'       => strval($api),
            'appkey'    => Config('Logisticskey.mabang_key.api_key'),
            'data'      => $reqParams,
            'timestamp' => $timestamp,
        ];
        $url      = Config('Logisticskey.mabang_key.url');
        $token    = self::get_authorization(['content'=>$data]);

        $response = HttpUtil::postUrlMaBang($url,$data,$token);
        $order_item = $response['data']['data'][0]['orderItem']??'';
        $arr        = [];
        if($order_item){
             foreach($order_item as $k=>$v){
                 $arr[$k]['platformSku']       = $v['platformSku']??'';
                 $arr[$k]['salesRecordNumber'] = $v['salesRecordNumber']??'';
             }
        }
        return $arr;
    }


    /**
     * @desc   拆分订单接口
     * @author luckyXiong
     * @date   2025-05-22
     */
    public function split_order($params=[]){
        $api        = 'order-do-split-order';
        $order_id   = $params['order_id']??'';
        //获取当前拆单的订单详情;
        $order_info = Db::name('order_info')
            ->field('id,shop_id,order_id,info_id,sku,quantity as num')
            ->where(['order_id'=>$order_id])
            ->where('sku','<>','')
            ->where('is_seel','<>',1)
            ->select()
            ->toArray();

        $split_arr = [];

        //获取行号;
        $arr_salesRecordNumber = self::get_salesRecordNumber(['platformOrderIds'=>$order_id]);
        $salesRecordNumber     = array_column($arr_salesRecordNumber,'salesRecordNumber','platformSku');
        foreach($order_info as $k=>$v){
            //获取当前订单的库存;
            $param = [
                'stockSkus' =>$v['sku'],
                'updateTime'=>date('Y-m-d',time()),
            ];
            $new_quantity = self::get_sku_stock($param);
            if($new_quantity>0){
                //组装待拆分可以发货的新数组的数据;
                $split_arr[$k]['stockSku']          = $v['sku'];
                $split_arr[$k]['quantity']          = $v['num'];
                $split_arr[$k]['salesRecordNumber'] = $salesRecordNumber[$v['sku']]??0;
            }
        }

        $response = '';
        if($split_arr){
            $split_arr = array_values($split_arr);
            $timestamp = strval(time());
            $data      =  [
                'api'       => strval($api),
                'appkey'    => Config('Logisticskey.mabang_key.api_key'),
                'data'      => [
                    'platformOrderId'=>$order_id,
                    'stockData'      =>json_encode($split_arr)
                ],
                'timestamp' => $timestamp,
            ];
            $url      = Config('Logisticskey.mabang_key.url');
            $token    = self::get_authorization(['content'=>$data]);
            $response = HttpUtil::postUrlMaBang($url,$data,$token);
            htmlLog(['params'=>$data,'response'=>$response],OPERATE_LOG . date('Ym') . '/mabang_split_order/' . date('Ymd') . '.txt');
            $new_order_id = $response['data']['platformOrderId']??'';
            //触发发货逻辑
            self::deliver_order([
                'platformOrderId'=>$new_order_id
            ]);
        }
        return $response;
    }



    /**
     * @desc   查看订单的发货状态
     * @author luckyXiong
     * @date   2025-06-04
     */
    public function get_order_list($params=[]){
        $api       = 'order-get-order-list-new';
        $reqParams = $params;
        $timestamp = strval(time());
        $data      =  [
            'api'       => strval($api),
            'appkey'    => Config('Logisticskey.mabang_key.api_key'),
            'data'      => $reqParams,
            'timestamp' => $timestamp,
        ];
        $url      = Config('Logisticskey.mabang_key.url');
        $token    = self::get_authorization(['content'=>$data]);
        $response = HttpUtil::postUrlMaBang($url,$data,$token);
        return   $response;
    }


    /**
     * @desc   订单发货处理
     * @author luckyXiong
     * @date   2025-06-05
     */
    public function deliver_order($params=[]){
        $api       = 'order-do-deliver-order';
        $reqParams = $params;
        $timestamp = strval(time());
        $data      =  [
            'api'       => strval($api),
            'appkey'    => Config('Logisticskey.mabang_key.api_key'),
            'data'      => $reqParams,
            'timestamp' => $timestamp,
        ];
        $url      = Config('Logisticskey.mabang_key.url');
        $token    = self::get_authorization(['content'=>$data]);
        $response = HttpUtil::postUrlMaBang($url,$data,$token);
        htmlLog(['params'=>$data,'response'=>$response],OPERATE_LOG . date('Ym') . '/deliver_order/' . date('Ymd') . '.txt');
        return   $response;
    }



}